package com.hisense.ovcloud.apicontrol.tool;

import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Slf4j
public class Encrypt2Utils {

    public static String String2SHA256StrJava(String str, String salt) throws NoSuchAlgorithmException {
        return String2SHA256StrJava(str + salt);
    }

    public static byte[] String2SHA256ByteJava(String str, String salt) throws NoSuchAlgorithmException {
        return String2SHA256ByteJava(str + salt);
    }

    /**
     * 利用java原生的摘要实现SHA256加密
     *
     * @param str 加密后的报文
     * @return
     */
    public static String String2SHA256StrJava(String str) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
        return byte2Hex(messageDigest.digest());
    }

    public static byte[] String2SHA256ByteJava(String str) throws NoSuchAlgorithmException {
        log.info("String2SHA256ByteJava, str:{}", str);
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
        return messageDigest.digest();
    }

    /**
     * 将byte转为16进制
     *
     * @param bytes
     * @return
     */
    public static String byte2Hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String temp;
        for (byte aByte : bytes) {
            temp = Integer.toHexString(aByte & 0xFF);
            if (temp.length() == 1) {
                //1得到一位的进行补0操作
                sb.append('0');
            }
            sb.append(temp);
        }
        return sb.toString();
    }
}
